import { useState } from 'react';

// 根据传入的字符串动态生成对象的键和类型
type ModalState = {
  isOpen: boolean;
  isLoading: boolean;
  open: () => void;
  close: () => void;
  startLoading: () => void;
  stopLoading: () => void;
};

// 类型定义：根据传入的数组定义返回对象的键
type ModalControls<ModalNames extends string> = Record<ModalNames, ModalState>;

function useModal<ModalNames extends string>(...names: ModalNames[]): ModalControls<ModalNames> {
  const [states, setStates] = useState<Record<string, { isOpen: boolean; isLoading: boolean }>>(
    Object.fromEntries(names.map((name) => [name, { isOpen: false, isLoading: false }])),
  );

  const modalControls = {} as ModalControls<ModalNames>;
  names.forEach((name) => {
    modalControls[name] = {
      isOpen: states[name]?.isOpen ?? false,
      isLoading: states[name]?.isLoading ?? false,
      open: () => setStates((s) => ({ ...s, [name]: { ...s[name], isOpen: true } })),
      close: () => setStates((s) => ({ ...s, [name]: { ...s[name], isOpen: false } })),
      startLoading: () => setStates((s) => ({ ...s, [name]: { ...s[name], isLoading: true } })),
      stopLoading: () => setStates((s) => ({ ...s, [name]: { ...s[name], isLoading: false } })),
    };
  });

  return modalControls;
}

export default useModal;
